package com.neusoft.huaniao.controller;

import org.springframework.web.bind.annotation.*;
import com.neusoft.huaniao.dao.CouponDao;
import com.neusoft.huaniao.model.Coupon;
import com.neusoft.huaniao.model.Orderdetail;
import com.neusoft.huaniao.model.Orders;
import com.neusoft.huaniao.model.User;
import com.neusoft.huaniao.service.OrderdetailService;
import com.neusoft.huaniao.service.OrdersService;
import com.neusoft.huaniao.service.UserService;
import com.neusoft.huaniao.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 订单Controller
 *
 */
@RestController
@RequestMapping("/orders")
public class OrdersController {
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private OrderdetailService orderdetailService;
	@Autowired
	private UserService userService;
	@Autowired
	private CouponDao couponDao;

	/**
	 * 新增订单
	 */
	@PostMapping("/insert")
	@Transactional
	public Result<String> insert(@RequestBody Orders orders) {
		BigDecimal orderTotalPrice=new BigDecimal(0);
		
		//计算总金额
		for(Orderdetail detail:orders.getOrderdetails()){
			BigDecimal totalprice = detail.getTotalprice();
			orderTotalPrice=orderTotalPrice.add(totalprice);
		}
		
		//扣除优惠券
		Coupon coupon=null;
		if(orders.getCouponid()!=null){
			coupon = couponDao.selectByPrimaryKey(orders.getCouponid());
			orderTotalPrice=orderTotalPrice.subtract(coupon.getCouponValue());
			System.out.println(coupon.getCouponValue().toString());
			//更改优惠券状态为已使用
			coupon.setCouponStatus(1);
			couponDao.updateByPrimaryKey(coupon);
		}
		
		//查询账户余额，和订单总金额比较
		User user = userService.selectByPrimaryKey(orders.getBuyerid());
		if(user.getMoney().compareTo(orderTotalPrice)!=1){
			return ResultGenerator.genFailResult("余额不足，扣款失败！");
		}
		
		//新增订单
		orders.setCreateTime(new Date());
		orders.setTotalPrice(orderTotalPrice);
		ordersService.insert(orders);
		
		//新增订单明细
		for(Orderdetail detail:orders.getOrderdetails()){
			detail.setOrderid(orders.getId());
			orderdetailService.insert(detail);
		}
		
		//扣款
		user.setMoney(user.getMoney().subtract(orderTotalPrice));
		userService.updateByPrimaryKey(user);
		
		return ResultGenerator.genSuccessResult();
	}

	/**
	 * 删除
	 */
	@GetMapping("/delete/{ids}")
	public Result<String> delete(@PathVariable("ids") String ids) {
		if (null == ids || ids.equals("")) {
			return ResultGenerator.genFailResult(null);
		}
		String str[] = ids.split(",");
		for (String s : str) {
			ordersService.deleteByPrimaryKey(Integer.valueOf(s));
		}
		return ResultGenerator.genSuccessResult();
	}

	/**
	 * 更新
	 */
	@PostMapping("/update")
	public Result<String> update(@RequestBody Orders orders) {
		int res = ordersService.updateByPrimaryKey(orders);
		if (res == 1) {
			return ResultGenerator.genSuccessResult();
		} else {
			return ResultGenerator.genFailResult(null);
		}
	}

	/**
	 * 主键查询
	 */
	@GetMapping("/info/{id}")
	public Result<?> selectById(@PathVariable("id") int id) {
		Orders orders = ordersService.selectByPrimaryKey(id);
		if (null == orders) {
			return ResultGenerator.genFailResult(null);
		} else {
			return ResultGenerator.genSuccessResult(orders);
		}
	}

	/**
	 * 分页查询
	 */
	@PostMapping("/search")
	public HashMap<String, Object> search(@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows, Orders orders, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (page != null && rows != null) {
			PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
			map.put("start", pageBean.getStart());
			map.put("size", pageBean.getPageSize());
		}

		List<Orders> list = ordersService.select(map);
		int total = ordersService.count(map);
		HashMap<String, Object> result = new HashMap<>();
		result.put("rows", list);
		result.put("total", total);
		return result;
	}
	
	
	/**
	 * 根据用户id查询订单
	 */
	@GetMapping("/selectByBuyerid/{buyerid}")
	public Result<?> selectByUserid(@PathVariable("buyerid")int buyerid){
		List<Orders> orders = ordersService.selectByUserid(buyerid);
		return ResultGenerator.genSuccessResult(orders);
	}
	
}